<template>
  <div class="map-tool">
    <div v-if="isLoading">
      <p>营收数据对接中，请稍候...</p>
    </div>
    <div
      class="piplineBrustContainer"
      style="position: absolute; top: -88vh; left: 79vw; color: #fff"
      v-if="isPipeBrustShow "
    >
      <PipelineBrust :dialogVisible="isPipeBrustShow" v-if="isPipeBrustShow"></PipelineBrust>
    
    </div>
    <div
      class="piplineBrustContainer"
      style="position: absolute; top: -88vh; left: 79vw; color: #fff"
      v-if="isClickInfoShow "
    >
    
      <ClickInfoShow
      v-if="isClickInfoShow"
      :dialogVisible="isClickInfoShow"
      @update:dialogVisible="isClickInfoShow = $event"
    ></ClickInfoShow>
    </div>
    <div class="map-coordinates">
      {{ coordinates }}
    </div>
    <div class="my-scale-line"></div>

    <!-- <el-select
      v-if="showMeasureSelect"
      v-model="selectedMeasureType"
      @change="handleMeasureTypeChange"
      placeholder="请选择"
    >
      <el-option label="长度测量" value="LineString"></el-option>
      <el-option label="面积测量" value="Polygon"></el-option>
    </el-select> -->
    <div class="elBtn">
      <el-button @click="toggleMeasureSelect">测量</el-button>
      <div class="chooseMeasure" v-if="showMeasureSelect">
        <button @click="handleMeasureTypeChange('LineString')">长度测量</button>
        <button @click="handleMeasureTypeChange('Polygon')">面积测量</button>
      </div>
      <el-button @click="clear">清除</el-button>
      <!-- <el-button @click="zoomIn">放大</el-button>
      <el-button @click="zoomOut">缩小</el-button> -->
      <el-button @click="resetView">复位</el-button>
      <el-button @click="isMapChange = !isMapChange">底图</el-button>
      <el-button @click="isKeyWordsShow = true">定位</el-button>
      <el-button @click="clickQuery">单点</el-button>
      <el-button @click="pipeLineAnalysis">爆管</el-button>
      <div class="mapChange" v-show="isMapChange">
        <div class="item" @click="changeMap('矢量')"><span>矢量</span></div>
        <div class="item" @click="changeMap('影像')"><span>影像</span></div>
        <!-- <div class="item"><span>地形</span></div> -->
      </div>
    </div>
    <div class="popup" ref="popup" style="pointer-events: none">
      <InfoPop
        ref="popInfo"
        v-show="isInfoPopShow"
        :dialogVisible="isInfoPopShow"
        @update:dialogVisible="isInfoPopShow = $event"
      ></InfoPop>
    </div>
    <UserEquipConnection
      style="position: absolute; top: -100vh; left: 0vw"
      v-show="isUserEquipShowPop"
      @update:dialogVisible="isUserEquipShow = $event"
    >
    </UserEquipConnection>
  
    <KeyWordsSearch
      style="position: absolute; top: -80vh; right: -97vw"
      v-if="isKeyWordsShow"
      @closeThis="isKeyWordsShow = $event"
    ></KeyWordsSearch>
    <UserDevicePop v-show="isUserDeviceSonShowPop"> </UserDevicePop>
  </div>
</template>

<script>
import KeyWordsSearch from "../QuickPosition/components/KeyWordsSearch.vue";
import ClickInfoShow from "../EquipmentManagement/components/ClickInfoShow.vue";
import UserDevicePop from "../EquipmentManagement/components/UserDevicePop.vue";
import UserEquipConnection from "../EquipmentManagement/components/UserEquipConnection.vue";
import PipelineBrust from "../PipelineAnalysis/component/PipelineBrust.vue";
import dmgis from "@/api/dmgis";
import ScaleLine from "ol/control/ScaleLine";
import { Image } from "ol/layer";
import Overlay from "ol/Overlay";
import InfoPop from "../MapTool/InfoPop.vue";
import { markRaw } from "vue";
import { transform, useGeographic, Projection, addProjection } from "ol/proj";
export default {
  name: "MapTool",
  components: {
    InfoPop,
    ClickInfoShow,
    PipelineBrust,
    UserDevicePop,
    UserEquipConnection,
    KeyWordsSearch,
  },
  data() {
    return {
      querySpatialLayer: null,
      isKeyWordsShow: false,
      isPipeBrustShow: false,
      isClickInfoShow: false,
      stateMap: "影像",
      coordinates: "0, 0", // 初始坐标
      map: null, // 地图实例
      scaleLineElement: null, // 比例尺 DOM 元素
      showMeasureSelect: false, // 控制测量下拉框的显示
      selectedMeasureType: "", // 选中的测量类型
      isMapChange: false,
      projectLayer: null,
      isInfoPopShow: false,
      popup: null,
      dmPipProjectLayer: null,
      selectedCoordinates: null,
       // 初始化 clickQueryData 为数组
       clickQueryDataPoint: [],
      clickQueryDataLine: [],
      clickCoord:[],
    };
  },
  methods: {
    clickQuery() {
      this.isClickInfoShow = !this.isClickInfoShow;
      let mapcontanier = document.querySelector(".ol-viewport");
      mapcontanier.style.cursor = "crosshair";
      // 添加地图点击事件监听器
      this.getPointListener = (event) => {
        mapcontanier.style.cursor = "wait";
        const coordinate = event.coordinate;
        // 存储点击位置的经纬度
        this.selectedCoordinates = {
          lon: coordinate[0],
          lat: coordinate[1],
        };
        this.map.marker.addMarker(
        this.selectedCoordinates.lon,
        this.selectedCoordinates.lat,
        this.querySpatialLayer,
        {
          scale: 1.5, //大小
          radius: 8,
          pBorderColor: "#000000",
          pBorderWidth: 1,
          pFillColor: "red",
        },
       
      );
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        var rect = new dmgis.object.Envelope();
        rect.minx = this.selectedCoordinates.lon - 1;
        rect.miny = this.selectedCoordinates.lat - 1;
        rect.maxx = this.selectedCoordinates.lon + 1;
        rect.maxy = this.selectedCoordinates.lat + 1;
        SpatialQuery.env = rect; //矩形
        getFeatureParams.sql = SpatialQuery;

        let flag = false;
        let that = this;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          mapcontanier.style.cursor = "auto";
          this.map.map.un("singleclick", this.getPointListener);
          return;
        }
        async function getFeatureByClcik() {
          let mapcontanier = document.querySelector(".ol-viewport");

          for (let item of layersAttribute) {
            console.log(item, "test");
            if (flag) {
              mapcontanier.style.cursor = "auto";
            }
            getFeatureParams.strlayername = item;
            await that.projectLayer
              .SendFeatureMapService(getFeatureParams)
              .then((res) => {
                console.log(res,"RES");
                if (res.objset) {
                  flag = true;
                }
                let feature = res;
                  if (feature.objset && feature.objset.length > 0) {
                    let firstFeature = feature.objset[0];
                    let objectData = {};
                    console.log(firstFeature, "单点查询返回请求");
                    if (firstFeature.rec.length > 0) {
                      firstFeature.rec.forEach((rec) => {
                        objectData[rec.fldname] = rec.fldval;
                      });

                      if (firstFeature.strPnt) {
                        objectData.typeOFdata = "device";
                        objectData.dataName =
                          objectData.node_prop ||
                          objectData.style ||
                          objectData.nodeProperty;
                        let points = firstFeature.strPnt.split(";");

                        // 然后分别处理每个坐标点，再计算中间值
                        let x_coords = [];
                        let y_coords = [];

                        points.forEach((point) => {
                          // 再次使用 split 方法将每个坐标点按空格分割成 x 和 y 值
                          let [x, y] = point.split(" ");
                          // 将 x 和 y 值分别添加到对应的数组中
                          x_coords.push(parseFloat(x));
                          y_coords.push(parseFloat(y));
                        });
                        objectData.x_coord = x_coords[0];
                        objectData.y_coord = y_coords[0];
                        that.clickCoord=[objectData.x_coord,objectData.y_coord];
                        // 将 objectData 添加到 clickQueryData 中
                        that.clickQueryDataPoint.push(objectData);
                      } else if (firstFeature.strCor) {
                        objectData.typeOFdata = "pipeline";
                        objectData.dataName =
                          (objectData.pipe_dia || objectData.pipeDiameter) +
                          "mm" +
                          "管线";
                        let points = firstFeature.strCor.split(";");

                        // 然后分别处理每个坐标点，再计算中间值
                        let x_coords = [];
                        let y_coords = [];

                        points.forEach((point) => {
                          // 再次使用 split 方法将每个坐标点按空格分割成 x 和 y 值
                          let [x, y] = point.split(" ");
                          // 将 x 和 y 值分别添加到对应的数组中
                          x_coords.push(parseFloat(x));
                          y_coords.push(parseFloat(y));
                        });

                        // 计算 x 和 y 的中间值
                        let x_coord = (x_coords[0] + x_coords[1]) / 2;
                        let y_coord = (y_coords[0] + y_coords[1]) / 2;
                        objectData.x_coord = x_coord;
                        objectData.y_coord = y_coord;
                        that.clickCoord=[objectData.x_coord,objectData.y_coord];
                        // 将 objectData 添加到 clickQueryData 中
                        that.clickQueryDataLine.push(objectData);
                      }
                    }
                  }
              });
              console.log(that.clickQueryDataPoint, "clickQueryDataPoint");
              console.log(that.clickQueryDataLine, "clickQueryDataLine");

              that.$store.commit(
                "setClickQueryDataPoint",
                that.clickQueryDataPoint
              );
              that.$store.commit(
                "setClickQueryDataLine",
                that.clickQueryDataLine
              );
          }
          if (!flag) {
            that.$message.warning("未查询到相关数据");
            mapcontanier.style.cursor = "auto";
          }
        }
        getFeatureByClcik();
        // 点击后移除事件监听器

        this.map.map.un("singleclick", this.getPointListener);
      };
      this.map.map.on("singleclick", this.getPointListener);
    },
    pipeLineAnalysis() {
      // this.$store.commit("setisPipeShow", true);
      this.isPipeBrustShow = true ;
    
    },
    changeMap(type) {
      this.setLayerVisibility(
        [`矢量地图瓦片`, `影像地图瓦片`, `地形地图瓦片`],
        false
      );
      this.stateMap = type;
      this.setLayerVisibility([`${this.stateMap}地图瓦片`], true);
    },
    setLayerVisibility(layerNameGroup, visible) {
      this.map.map
        .getLayers()
        .getArray()
        .forEach((layer) => {
          if (layerNameGroup.includes(layer.get("layerName"))) {
            layer.setVisible(visible);
          }
        });
    },

    initMap() {
      setTimeout(() => {
        this.map = this.$store.getters.Map;
        if (this.map) {
          this.querySpatialLayer =
          this.map.layer.createVectorLayer("空间查询点图层");
          this.map.map.on("pointermove", this.updateCoordinates);
          this.projectLayer = this.$store.getters.projectLayer;
          this.initScaleLine();
          if (this.popup == null) {
            let elPopup = this.$refs.popup;
            this.popup = new Overlay({
              element: elPopup,
              position: null,
              offset: [0, -10],
              positioning: "bottom-center",
            });
            this.map.map.addOverlay(this.popup);
            let projection_szbj54 = new Projection({
              code: "sz2000",
              units: "m",
            });
            this.dmPipProjectLayer = new dmgis.olmap.PipLayer(
              "pipeLineNet",
              process.env.VUE_APP_BASE_API + "/dmgis",
              {
                maxZoom: 18,
                minZoom: 0,
                opacity: 1,
                projection: projection_szbj54,
              }
            );

            this.$store.commit(
              "setPipProjectLayer",
              markRaw(this.dmPipProjectLayer)
            );
          }
        } else {
          console.error("地名搜索定位地图实例未找到");
        }
      }, 500); // 延迟 1000 毫秒（1秒）后执行
    },
    // 初始化地图比例尺
    initScaleLine() {
      this.scaleLineElement = document.createElement("div");
      this.scaleLineElement.className = "my-scale-line";
      document
        .querySelector(".map-tool .my-scale-line")
        .appendChild(this.scaleLineElement);

      let scaleLineControl = new ScaleLine({
        className: "my-scale-line",
        target: this.scaleLineElement,
      });
      scaleLineControl.setUnits("metric");
      this.map.map.addControl(scaleLineControl);
    },
    // 切换测量下拉框的显示
    toggleMeasureSelect() {
      this.showMeasureSelect = !this.showMeasureSelect;
      this.map.interaction.clearPolygon();
    },
    // 处理测量类型的选择
    handleMeasureTypeChange(type) {
      if (!this.map.interaction.drawLayer) {
        this.map.interaction.initDraw("绘制图层");
      }
      this.map.interaction.addDraw(type, 1);
    },

    // 放大地图
    zoomIn() {
      if (this.map) {
        const view = this.map.map.getView();
        const zoom = view.getZoom();
        view.setZoom(zoom + 1);
      }
    },
    // 缩小地图
    zoomOut() {
      if (this.map) {
        const view = this.map.map.getView();
        const zoom = view.getZoom();
        view.setZoom(zoom - 1);
      }
    },
    // 复位地图视图
    resetView() {
      // console.log(this.map.map.getView().calculateExtent(),"this.map.map.getView().calculateExtent()");

      if (this.map) {
        this.map.panTo([314497.81, 655844.5], 13);
      }
    },
    // 更新坐标
    updateCoordinates(event) {
      const coordinate = event.coordinate;
      this.$store.commit("setCoordinate", {
        X: coordinate[0].toFixed(2),
        Y: coordinate[1].toFixed(2),
      });
      // 转换为 X: 经度, Y: 纬度的形式，并限制小数位数为2
      this.coordinates = `X: ${coordinate[0].toFixed(
        2
      )}, Y: ${coordinate[1].toFixed(2)}`;
    },
    //清除所有图层
    clear() {
      this.map.interaction.clearPolygon();
      let noClearGroup = [
        "矢量图层组",
        "影像图层组",
        "地形图层组",
        "基础地图瓦片",
      ];
      let layerGroup = this.map.map.getLayers().getArray();
      layerGroup.forEach((layer) => {
        if (
          !noClearGroup.includes(layer.get("name")) &&
          !noClearGroup.includes(layer.get("layerName"))
        ) {
          if (layer instanceof Image) {
            this.map.map.removeLayer(layer);
          } else {
            layer.getSource().clear();
          }
        }
      });
    },
  },
  computed: {
    // isInfoPopShow(){
    //   return this.$store.state.isInfoPopShow1;
    // },
    isLoading() {
      return this.$store.state.isLoading;
    },
    queryDataList(){
      return this.$store.state.detailDataPopList;
    },
    isEquipShow() {
      // 返回 prop 的值
      return this.dialogVisible;
    },
    isUserEquipShowPop() {
      return this.$store.state.isUserEquipShow;
    },
    isUserDeviceSonShowPop() {
      return this.$store.state.isUserDeviceSonShow;
    },
  },
  watch: {
    queryDataList(newVal) {
    
    this.isInfoPopShow = false;
   let detailDataContent=[];
    newVal.rec.forEach((item) => {
      detailDataContent[item.fldname] = item.fldval;
    });
   console.log(detailDataContent,"queryDataListMapTool获取到的值")
   if (detailDataContent.strCor) {
  // 解析 strCor 字符串
  const strCor = detailDataContent.strCor;
  const coordinates = strCor.split(";").map(point => point.split(" ").map(Number));

  // 计算 x 和 y 的中点
  let sumX = 0;
  let sumY = 0;
  coordinates.forEach(([x, y]) => {
    sumX += x;
    sumY += y;
  });

  const midX = sumX / coordinates.length;
  const midY = sumY / coordinates.length;

  // 将中点坐标赋值给 this.rowClickCoor
  this.rowClickCoor = {
    x_coord: midX,
    y_coord: midY
  };

  console.log(this.rowClickCoor, "this.rowClickCoor");
}
    if (this.popup) {
      //弹窗赋值
      let coordinatePoint = [
        detailDataContent.x_coord,
        detailDataContent.y_coord,
      ];
      this.popup.setPosition(coordinatePoint);
      this.map.panTo(coordinatePoint);
      this.isInfoPopShow = true;
     
    }
  },
  },
  mounted() {
    this.initMap();
    this.$store.commit("setshowValveOperate", false);
    // this.rightClickCopyCoor();
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听器
    if (this.map) {
      this.map.map.un("pointermove", this.updateCoordinates);
      this.map.map.removeLayer(this.querySpatialLayer);
    }
    this.clear();
  },
};
</script>

<style scoped>
.contextmenu {
  position: absolute;
  background-color: white;
  border: 1px solid #cccccc;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  padding: 5px;
  z-index: 1000;
}
.ol-contextmenu item {
  cursor: pointer;
  padding: 5px 10px;
}
.ol-contextmenu item:hover {
  background-color: #eee;
}
.map-tool {
  position: absolute;
  bottom: -1rem;
  left: 2rem;
}

.map-coordinates {
  /* 坐标显示样式 */
  position: absolute;
  bottom: -2rem;
  right: -84rem;
}

::v-deep .el-select {
  position: absolute;
  top: -86vh;
  left: 1vw;
  z-index: 3;
  width: 8vw;
}
::v-deep .el-input__inner {
  color: white;
  background-color: #236ca8d0;
}

/* 比例尺控件样式 */
.my-scale-line {
  position: absolute;
  right: -200px;
  font-weight: 700;
  font-size: 12px;
  color: black;
  bottom: -33px;
  left: auto;
  border: 2px solid black;
  border-top: none;
  text-align: center;
  background-color: hsla(0, 0%, 100%, 0);
  height: 8px;
  line-height: 0;
}
.elBtn {
  z-index: 3;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  position: absolute;
  top: -86vh;
  left: -2vw;
  .chooseMeasure {
    position: absolute;
    right: -5rem;
    display: flex;
    flex-direction: column;
    button {
      cursor: pointer;
      border-radius: 3px;
      flex-shrink: 0;
      padding: 3px 7px;
      border-bottom: none;
      background: #236ca8d0 !important;
      border: 1px solid #0090dee5;
      color: white;
    }
  }
  /* 按钮样式 */
  .el-button {
    flex-shrink: 0; /* 防止按钮在小屏幕上被压缩 */
    padding: 12px 7px;
    border-bottom: none;
    background: #236ca8d0 !important;
    border: 1px solid #0090dee5;
    color: white;
  }
  .el-button:hover {
    background: #3690c1e5 !important;
    color: white;
  }
  .el-button:focus {
    background: #3690c1e5 !important;
    color: white;
  }
  /* 第一个按钮不需要底部间距 */
  .el-button:last-child {
    margin-bottom: 0;
  }
  /* 最后一个按钮不需要底部间距 */
  .el-button:last-child {
    margin-bottom: 0;
  }
  .el-button + .el-button,
  .el-checkbox.is-bordered + .el-checkbox.is-bordered {
    margin-left: 0px;
  }
  .mapChange {
    width: 50px;
    /* height: 65px; */
    position: absolute;
    right: -3rem;
    top: 112px;
    background: #236ca8d0;

    .item {
      height: 30px;
      cursor: pointer;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #0090dee5;
      /* background-color: #236ca8d0; */
    }
    .item:hover {
      background: #3690c1e5;
      border: 1px solid #fff;
    }
  }
}
</style>
